using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using WalkingTec.Mvvm.Core;
using TyMES.PassStationCommunication;
using TyMES.Model.BaseInformation;
using MediatR;
using TyMES.Model.Record;
using Microsoft.AspNetCore.SignalR;
using TyMES.MidWare;
using TyMES.TemporaryClass;
using Microsoft.EntityFrameworkCore;

namespace TyMES.Services
{

    public class GlueDurationInspectionService
    {
        private readonly ILogger logger;
        private readonly WTMContext context;
        private readonly IHubContext<NotificationHub> notification;


        public GlueDurationInspectionService(ILogger<PassStationService> logger, WTMContext context, IHubContext<NotificationHub> notificationHub)
        {
            this.logger = logger;
            this.context = context;
            this.notification = notificationHub;
        }

        /// <summary>
        /// 进站涂胶检测，如果涂胶超时标志位为true则拒绝进站
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseComBool> ComeinGlueDurationInspection()
        {
            try
            {
                bool success=false;
                string mesg = "";
                string glueInspectionTimeoutFlag = await context.DC.Set<CustomConfig>().Where(x => x.customProperty == "GlueInspectionTimeoutFlag").Select(x => x.propertyValue).FirstOrDefaultAsync();
                if (glueInspectionTimeoutFlag != null)
                {
                    if (glueInspectionTimeoutFlag == "true")
                    {
                        success = false;
                        mesg = "涂胶检测超时，拒绝进站";
                    }
                    else if (glueInspectionTimeoutFlag == "false")
                    {
                        success = true;
                        mesg = "涂胶检测未超时";
                    }
                    else 
                    {
                        success = false;
                        mesg = "涂胶检测超时标志异常值:" + $"[{glueInspectionTimeoutFlag}]" + "，请检查数据库数据是否异常";
                    }
                }
                else
                {
                    success = false;
                    mesg = "涂胶检测超时标志为空，请维护数据库数据";
                }
                var response = new ResponseComBool
                {
                    Success = success,
                    Mesg = mesg
                };
                return response;
            }
            catch (Exception ex)
            {
                var response = new ResponseComBool
                {
                    Success = false,
                    Mesg = ex.ToString()
                };
                return response;
            }
        }

        public async Task<ResponseComBool> PassinGlueDurationInspection(string snNumber)
        {
            try
            {
                bool success = false;
                string mesg = "";
                
                // 查找涂胶工位配置
                string glueStationCode = await context.DC.Set<CustomConfig>().Where(x => x.customProperty == "GlueStation").Select(x => x.propertyValue).FirstOrDefaultAsync();
                if (glueStationCode == null)
                {
                    success = false;
                    mesg = "涂胶工位配置为空，请维护数据库数据";
                }
                else
                {
                    // 查找对应的涂胶出站记录
                    var gluePassRecord = await context.DC.Set<PassStationRecord>()
                        .Where(x => x.SnNumber == snNumber && x.StationCode == glueStationCode && x.PassStatus == "pass" && x.ReqType == "2")
                        .OrderByDescending(x => x.ID)
                        .FirstOrDefaultAsync();
                    
                    if (gluePassRecord == null)
                    {
                        success = false;
                        mesg = $"未找到SN:{snNumber}在涂胶工位:{glueStationCode}的出站记录";
                    }
                    else
                    {
                        // 检查出站时间是否超过3分钟
                        if (!string.IsNullOrEmpty(gluePassRecord.PassEndTime))
                        {
                            if (DateTime.TryParse(gluePassRecord.PassEndTime, out DateTime passEndTime))
                            {
                                var timeDifference = DateTime.Now - passEndTime;
                                if (timeDifference.TotalMinutes > 3)
                                {
                                    success = false;
                                    mesg = $"涂胶出站时间超过3分钟，出站时间:{passEndTime:yyyy-MM-dd HH:mm:ss}，当前时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}";
                                }
                                else
                                {
                                    success = true;
                                    mesg = "涂胶出站时间检测通过";
                                }
                            }
                            else
                            {
                                success = false;
                                mesg = $"涂胶出站记录的结束时间格式错误，无法解析时间:{gluePassRecord.PassEndTime}";
                            }
                        }
                        else
                        {
                            success = false;
                            mesg = $"涂胶出站记录的结束时间为空，记录ID:{gluePassRecord.ID}";
                        }
                    }
                }
                
                // 在返回前调用updateGlueTimeoutFlag，如果结果为false则传入true
                if (!success)
                {
                    var response2= await updateGlueTimeoutFlag(true);
                    if(response2.Success==false)
                    {
                        mesg += response2.Mesg;
                    }
                }
                
                var response = new ResponseComBool
                {
                    Success = success,
                    Mesg = mesg
                };
                return response;
            }
            catch (Exception ex)
            {
                var response = new ResponseComBool
                {
                    Success = false,
                    Mesg = ex.ToString()
                };
                return response;
            }
        }

        public async Task<ResponseComBool> updateGlueTimeoutFlag(bool isTimeout)
        {
            try
            {
                var timeoutFlagConfig = await context.DC.Set<CustomConfig>().Where(x => x.customProperty == "GlueInspectionTimeoutFlag").FirstOrDefaultAsync();
                if (timeoutFlagConfig != null)
                {
                    timeoutFlagConfig.propertyValue = isTimeout ? "true" : "false";
                    await context.DC.SaveChangesAsync();
                    
                    // 发送 SignalR 通知到涂胶工位
                    try
                    {
                        // 查询涂胶工位配置
                        string glueStationCode = await context.DC.Set<CustomConfig>().Where(x => x.customProperty == "GlueStation").Select(x => x.propertyValue).FirstOrDefaultAsync();
                        if (!string.IsNullOrEmpty(glueStationCode))
                        {
                            // 查询涂胶工位的产线信息
                            var station = await context.DC.Set<Station>().Where(x => x.StationCode == glueStationCode).FirstOrDefaultAsync();
                            if (station != null)
                            {
                                await notification.Clients.All.SendAsync("ReceiveMessage", new Notice(station.LineCodeId, glueStationCode));
                            }
                        }
                    }
                    catch (Exception notificationEx)
                    {
                        logger.LogError(notificationEx, "发送涂胶状态更新通知失败");
                    }
                    
                    return new ResponseComBool
                    {
                        Success = true,
                        Mesg = $"涂胶检测超时标志已更新为: {timeoutFlagConfig.propertyValue}"
                    };
                }
                else
                {
                    return new ResponseComBool
                    {
                        Success = false,
                        Mesg = "未找到涂胶检测超时标志配置，请检查数据库配置"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ResponseComBool
                {
                    Success = false,
                    Mesg = $"更新涂胶检测超时标志异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取涂胶检测超时状态
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseComBool> getGlueTimeoutFlag()
        {
            try
            {
                string glueInspectionTimeoutFlag = await context.DC.Set<CustomConfig>().Where(x => x.customProperty == "GlueInspectionTimeoutFlag").Select(x => x.propertyValue).FirstOrDefaultAsync();
                if (glueInspectionTimeoutFlag != null)
                {
                    bool isTimeout = glueInspectionTimeoutFlag == "true";
                    return new ResponseComBool
                    {
                        Success = isTimeout,
                        Mesg = glueInspectionTimeoutFlag
                    };
                }
                else
                {
                    return new ResponseComBool
                    {
                        Success = false,
                        Mesg = "涂胶检测超时标志配置不存在"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ResponseComBool
                {
                    Success = false,
                    Mesg = ex.ToString()
                };
            }
        }

        //public async Task<bool> stationlogadd(StationLogRecord stationLog, string linecode, string stationCode, string sn, string logtype, string mesg)
        //{
        //    stationLog.LogType = logtype;
        //    stationLog.StationCode = stationCode;
        //    stationLog.LineCode = linecode;
        //    stationLog.Log = mesg;
        //    stationLog.CreateTime = DateTime.Now;
        //    stationLog.Date_Time = DateTime.Now;
        //    context.DC.Set<StationLogRecord>().Add(stationLog);
        //    await context.DC.SaveChangesAsync();
        //    await notification.Clients.All.SendAsync("ReceiveMessage", new Notice(linecode, stationCode));
        //    return true;
        //}
    }
}
